/*
 *                  BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 * 
 * Created on Mar 21, 2006
 *
 */
package org.biojava.services.das2;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.biojava.bio.program.das.dasalignment.DASException;
import org.biojava.dasobert.das2.Das2Source;
import org.biojava.dasobert.dasregistry.DasCoordinateSystem;
import org.biojava.dasobert.dasregistry.DasSourceValidator;
import org.biojava.services.das.registry.DasRegistrySql;
import org.biojava.services.das.dao.*;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Das2SourceStore {
    
    public static Logger logger =  Logger.getLogger("org.biojava.services.das.registry");
    
    DataSource dataSource;
    
    public Das2SourceStore() {
        super();
        
        
        try {
            Context env = (Context) new InitialContext().lookup("java:comp/env");
            logger.info("init dataSource");
            dataSource = (DataSource) env.lookup(DasRegistrySql.DATASOURCE_NAME);
            if (dataSource == null) {
                logger.severe("could not obtain the dataSource - there will be serious problems. is the config correct?");
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    
    
    private int storeSource(Connection conn,Das2Source ds) throws SQLException {
        //das2source_id | adminemail        | description           | passkey | registerDate 
        //| leaseDate           | helperurl                                                                                                                           | nickname        | prefix | alert_admin | alert_sent | protocol | sourceurl                                      | baseurl                                
        
        // create placeholder in registry table;
        
	DasSourceManager dao = new DasSourceManager();

        int passkey = DasSourceManager.generatePasskey();
        
        String insregistry = "insert into registry (protocol,passkey,registerDate,leaseDate) " +
        " values (2,?,now(),now())";
        
        PreparedStatement psr = conn.prepareStatement(insregistry);
        psr.setInt(1,passkey);
        
        psr.executeUpdate();
        
        ResultSet rs = psr.getGeneratedKeys();
        int auto_id = -1;
        if (rs.next()) {
            auto_id= rs.getInt(1);
        }
        // todo - add coordinatesystem = testcodes ...
        
        String ins = "insert into das2source (adminemail,description,passkey, registerDate,"+
        " leasedate,helperurl,auto_id,nickname)" +
        " values (?,?,?,now(),now(),?,?,?)";
        
        PreparedStatement ps = conn.prepareStatement(ins);
        ps.setString(1,ds.getAdminemail());
        ps.setString(2,ds.getDescription());
        ps.setInt(3,passkey);
        ps.setString(4,ds.getHelperurl());
        ps.setInt(5,auto_id);
        ps.setString(6,ds.getNickname());
        ps.executeUpdate();
        
        
        
        //ds.setId()
        DasCoordinateSystem[] cs_types = ds.getCoordinateSystem();
        BeanFactory ctx=(new ClassPathXmlApplicationContext("SpringDAO.xml"));
		DasRegistrySql registry=(DasRegistrySql)ctx.getBean("registryBean");
        for( int i=0; i < cs_types.length; i++){
            
            DasCoordinateSystem cs = cs_types[i];
            dao.selectInsertCoordinateSystem(conn,cs,auto_id,null);          
        }
        
        String[] labels = ds.getLabels();
        
        dao.insertLabels(conn,auto_id,labels);
        
        return passkey ;
        
    }
    
    
    public int store(Das2Source ds) throws DASException {
        
        DasSourceValidator validator = new DasSourceValidator();
        validator.validateDasSource(ds);
        //boolean status = true;
        
        
        int passkey = -1;
        
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            passkey = storeSource(conn,ds);
            
            
        } catch (Exception e){
            e.printStackTrace();
           // status = false;
            
        }
        finally {
            if ( conn != null) {
                try { 
                    conn.close() ; 
                } catch (SQLException e){
                    e.printStackTrace();
                    //status = false;
                }
                
            }
        }
        
        return passkey;
        
    }
    
}
